<?php

class SiteController extends Controller
{
	public $layout='main';
	public $title;
	public $meta;
	public $bread = array();

	/**
	 * Declares class-based actions.
	 */
	public function actions() {
		return array(
				'page' => array(
						'class' => 'CViewAction',
				)
		);
	}
	public function __construct(){
		$this->isOnline(); // check website status
	}
	
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError(){
		
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('site/error', $error);
	    }
	}
	/*
	 * display home page
	 */
	public function actionIndex(){
		$this->title = Yii::app()->name." - The World's Leader in Data-Research-Innovation";
		$this->render('site/index');
	}
	
	/**
	 * Displays the contact page
	 */
	public function actionContact(){
		
		
		$model = new Contacts;
		
		$this->performAjaxValidation($model);
		
		if(isset($_POST['Contacts'])) {
			$model->attributes = $_POST['Contacts'];
			$model->referrer = $_SERVER["HTTP_REFERER"];
			$model->created = date('Y-m-d H:i:s');
			
			$ip = $_SERVER['REMOTE_ADDR'];
			$details = json_decode(@file_get_contents("http://ipinfo.io/{$ip}/json"));
			
			if ( isset($details) && !empty($details) ){
				$city = ( isset($details->city) && !empty($details->city) ) ? $details->city : '';
				$region = ( isset($details->region) && !empty($details->region) ) ? $details->region : '';
				$country = ( isset($details->country) && !empty($details->country) ) ? $details->country : '';
				
				$model->location = $details->ip.", ".$city.", ".$region.", ".$country;
			}
			
			if ( isset($_POST['Contacts']['type']) && !empty($_POST['Contacts']['type']) && ($model->type == 3 || $model->type == 4 || $model->type == 5) ){
				if($model->save()){
					Yii::app()->user->setState('model',$model);
					$this->redirect($this->createUrl('site/contact/thanks'));
				}
			} else {
				if($model->save())
				{
				//	$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				//	mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
					echo CJSON::encode(array(
	                                  'status'=>'success'
	                             ));
					
					Yii::app()->user->setState('model',$model);
					Yii::app()->end();
					
				} else{
					$error = CActiveForm::validate($model);
	                if($error!='[]')
	                	echo $error;
	                    Yii::app()->end();
				}	
			}
			
			
		}
		$this->render('site/contact',array('model'=>$model));
	}
	/**
	 * @param unknown $slug
	 * @param string $mainSlug
	 * function to display pages
	 */
	
	public function actionPage($slug){
		if ( isset($slug) && !empty($slug) ){
			$content = Cms::model()->findByAttributes(array('slug'=>$slug,'status'=>'1'));
			if($content){
				$this->meta = $content;
				$this->title = $content->meta_title;
				if ( $slug === 'view-datacards'){
					$datacards = Cms::model()->findAllByAttributes(array('status'=>'1','is_datacard'=>'1'), array('order'=>'title ASC'));
					$this->render('site/datacards',array('page'=>$content, 'datacards'=>$datacards));
					Yii::app()->end();
				}
				$this->render('site/page',array('page'=>$content));
			} else {
				$this->render('site/error',array('code'=>'404'));
			}
		} else {
			$this->redirect('/');
		}
		
	}
	/**
	 * 
	 * @param integer page id in Menuitems table
	 */
	public function breadcrumb($id, $slug=null){
		
		if ( isset($id) && !empty($id) ){
			$menuId = Menuitems::model()->findByPk($id);
			if (isset($menuId) && !empty($menuId) ){
				
				$cms = Cms::model()->findByPk($menuId->page_id);
				
				if ($cms->slug == $slug){
					$this->bread[] = ucwords($cms->title);
				} else{
					$this->bread[ucwords($cms->title)] = $this->createUrl('site/page',array('slug'=>$cms->slug));
				}
				
				if($menuId->parent != 0){
					$this->breadCrumb($menuId->parent);
				}
			}
			return array_reverse($this->bread);
		}
	}
	/**
	 * function to recieve newsletter subscription
	 */
	public function actionNewsletter(){
		if ( isset($_POST['Newsletters']) && !empty($_POST['Newsletters']) ){
			$model = new Newsletters();
			$model->attributes = $_POST['Newsletters'];
			$model->created = date('Y-m-d H:i:s');
			
			if ($model->save()){
				echo CJSON::encode(array(
						'status'=>'success'
				));
				Yii::app()->end();
			} else{
				$error = CActiveForm::validate($model);
                if($error!='[]')
             		echo $error;
                    Yii::app()->end();
			}
		}
	}
	
	public function actionSitemap(){
		$this->render('site/sitemap');
	}
	public function actionCareers(){
		$this->render('site/sitemap');
	}
	
	public function actionSearch($keyword){
		if (isset($keyword) && !empty($keyword)){
			
			$model = new Cms();
			$model->unsetAttributes();
			$keyword = strip_tags(htmlspecialchars_decode($keyword));
			$results = $model->keywordSearch($keyword);
			$ids = $contents = array();
			foreach($results as $result){
				$ids[$result->title] = $result->slug;
				$contents[] = $result->content;
			}
			$this->render('site/search',array('ids'=>array_unique($ids), 'contents'=>$contents, 'keyword'=>$keyword));
			
		} else {
			$this->redirect(Yii::app()->getBaseUrl());
		}
	}
	
	/**
	 * Request a quote page
	 */
	public function actionRequestQuote(){
		
		$model = new Quotes;
		
		$this->performAjaxValidation($model);
		
		if(isset($_POST['Quotes'])) {
			$model->attributes = $_POST['Quotes'];
			$model->created = date('Y-m-d H:i:s');
				
			if($model->save())
			{
				//	$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				//	mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				echo CJSON::encode(array(
						'status'=>'success'
				));
		
				Yii::app()->user->setState('model',$model);
				Yii::app()->end();
		
			} else{
				$error = CActiveForm::validate($model);
				if($error!='[]')
					echo $error;
				Yii::app()->end();
			}
				
		}
		
		$this->render('site/quote',array('model'=>$model));
		
	}
	
	/**
	 * Signup newsletter page
	 */
	public function actionSignup(){
	
		$model = new Newsletters();
	
		$this->performAjaxValidation($model);
	
		if(isset($_POST['Newsletters'])) {
			$model->attributes = $_POST['Newsletters'];
			$model->created = date('Y-m-d H:i:s');
	
			if($model->save())
			{
				echo CJSON::encode(array(
						'status'=>'success'
				));
	
				Yii::app()->user->setState('model',$model);
				Yii::app()->end();
	
			} else{
				$error = CActiveForm::validate($model);
				if($error!='[]')
					echo $error;
				Yii::app()->end();
			}
	
		}
	
		$this->render('site/signup',array('model'=>$model));
	
	}
	
	public function actionJoinReseller(){
		
		
		$model = new Resellers();
		
		$this->performAjaxValidation($model);
		
		if(isset($_POST['Resellers'])) {
			$model->attributes = $_POST['Resellers'];
			$model->created = date('Y-m-d H:i:s');
		
			if($model->save())
			{
				echo CJSON::encode(array(
						'status'=>'success'
				));
		
				Yii::app()->user->setState('model',$model);
				Yii::app()->end();
		
			} else{
				$error = CActiveForm::validate($model);
				if($error!='[]')
					echo $error;
				Yii::app()->end();
			}
		
		}
		
		$this->render('site/resellers',array('model'=>$model));
		
		
	}
	
	/**
	 * 
	 * @param Object $model
	 * Ajax validation of form data
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && ( $_POST['ajax']==='contact-form' || $_POST['ajax']==='contacts-form'))
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
